﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace update
{
    public partial class Form1 : Form
    {
        public Form1()
        {
         
            InitializeComponent();
           
        }
        public  bool Delay(int delayTime)
        {
            DateTime now = DateTime.Now;
            int s;
            do
            {
                TimeSpan spand = DateTime.Now - now;
                s = spand.Seconds;
                Application.DoEvents();
            }
            while (s < delayTime);
            return true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string path = System.IO.Directory.GetCurrentDirectory();
            HttpDldFile df = new HttpDldFile();
            XmlDocument xdcConfig = new XmlDocument();
            try
            {
                xdcConfig.Load("config/downConfig.xml");
                string version = xdcConfig.SelectSingleNode("//version/@url").Value;
                string download = xdcConfig.SelectSingleNode("//download/@url").Value;


                string localv = "";

                XmlDocument xdclccal = new XmlDocument();
                if (File.Exists(path + "/version.xml"))
                {

                    xdclccal.Load(path + "/version.xml");
                    localv = xdclccal.InnerText;
                }
                bool down = df.Download(version, path + "/version_temp.xml");
                XmlDocument xdc = new XmlDocument();
                xdc.Load(path + "/version_temp.xml");
                string serv = xdc.InnerText;

                if (serv != localv)
                {
                    File.Delete(path + "/version.xml");

                    df.Download(download, path + "/debug.zip");
                    listBox1.Items.Add("开始解压文件");
                    HttpDldFile.UnZip(path + "/debug.zip", path + "/");
                    listBox1.Items.Add("解压完成");
                    File.Delete(path + "/debug.zip");
                    listBox1.Items.Add("重新启动主界面");
                    xdclccal = null;
                    down = df.Download(version, path + "/version.xml");

                    File.Delete(path + "/version_temp.xml");

                    //FileInfo fi = new FileInfo(path + "/version_temp.xml");
                    //fi.MoveTo(path + "/version.xml");

                }
                if (Delay(1))
                {

                    System.Diagnostics.Process.Start(Application.StartupPath + "/print.exe");
                    System.Diagnostics.Process procc = System.Diagnostics.Process.GetCurrentProcess();
                    procc.Kill();
                }
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
    }
}
